<template>
  <div>
    <el-dialog :visible.sync="dialogVisible" custom-class="endClassDialog">
      <div class="endClassDialog_content" v-if="dialogVisible" v-loading="getReportLoading"
        :close-on-click-modal="false">
        <div class="title">课程概况</div>
        <div class="courseName" :title="`《${currItem.name}》`">
          《{{ currItem.name }}》
        </div>
        <div class="endClassDialogInfo">
          <div class="endClassDialogInfo_left">
            <div class="chooseCourseCount">
              本期选修人数为：{{ courseData.totalStuCount }}（人）
            </div>
            <div class="taskStus">
              <div class="finishTaskCount">
                已完成全部任务:{{ courseData.finishStuCount }}（人）
              </div>
              <div class="uFinishTaskCount">
                未完成全部任务:{{ courseData.notFinishStuCount }}（人）
              </div>
            </div>
            <div class="reviewTask">
              <div class="FinishreviewTask">
                已批阅任务：{{ courseData.hasMarkTaskCount }}
              </div>
              <div class="uFinishreviewTask">
                未批阅任务：{{ courseData.notMarkTaskCount }}
              </div>
            </div>
            <div class="scoreCount">
              <div class="cBlack">及格人数：{{ courseData.passStuCount }}</div>
              <div class="cBlack">
                不及格人数：{{ courseData.notPassStuCount }}
              </div>
              <div class="score">最高分：{{ courseData.maxScore }} 分</div>
              <div class="score">最低分：{{ courseData.minScore }} 分</div>
              <div class="score">平均分：{{ courseData.avgScore }} 分</div>
            </div>
            <div class="courseInfo">
              <div class="teacher">
                主讲教师：{{ currItem.tutorStaffUserName }}
              </div>
              <div class="taskCoutn">
                课程任务数：{{ courseData.totalTaskCount }} 项
              </div>
              <div class="courseTime">课程时长：0 课时</div>
              <div class="courseCredit">课程学分：0</div>
            </div>
          </div>
          <div class="endClassDialogInfo_right">
            <div>
              <div class="title">任务完成度：</div>
              <div class="percentage">
                {{
                (courseData.finishStuCount / courseData.totalStuCount)
                | rounding
                }}%
              </div>
            </div>
            <div>
              <div class="title">批阅完成度：</div>
              <div class="percentage">
                {{
                (courseData.hasMarkTaskCount / courseData.totalTaskCount)
                | rounding
                }}%
              </div>
            </div>
            <div>
              <div class="title">及格率：</div>
              <div class="percentage">
                {{
                (courseData.passStuCount / courseData.totalStuCount)
                | rounding
                }}%
              </div>
            </div>
          </div>
        </div>
        <div class="checkInfoBtn">
          <button @click="handleToCourseStatistics">查看详情</button>
        </div>
        <div class="endClassBtn-cancel">
          <button class="endClassBtn" @click="handleEnd" v-if="currItem.state !== '已结课'">
            <!-- v-if="currItem.state !== '已结课不可选' || currItem.state !== '已结课'" -->
            结课
          </button>
          <button class="cancelEndClassBtn" @click="cancelEndClass" v-else>
            取消结课
          </button>

          <button class="cancel" @click="handleClose">返回</button>
        </div>
        <el-dialog :visible.sync="beforeEndDialog" custom-class="checkBeforeEndState" append-to-body
          :close-on-click-modal="false">
          <div v-loading="autoScoring">
            <div class="tips">
              {{
              courseData.notMarkTaskCount > 0
              ? "有未批阅的任务"
              : courseData.notFinishStuCount > 0
              ? "有未完成任务的学生"
              : "该课程可以结课"
              }}
            </div>
            <div v-if="
                (showState === 'noMarkTask' && courseData.notMarkTaskCount > 0) || (showState === 'notFinishStu' && courseData.notFinishStuCount > 0)
              ">
              <span>结课前需要将所有任务批阅，是否需要自动批阅所有任务？系统分数的默认中位数：{{
                form.defaultTaskScore
                }}，随机波动分数：{{ form.varmark }}</span>
              <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="默认分数：" prop="defaultTaskScore">
                  <el-input v-model="form.defaultTaskScore" size="small" placeholder="请输入默认分数"></el-input>
                </el-form-item>
                <el-form-item label="波动分数：" prop="varmark">
                  <el-input v-model="form.varmark" size="small" placeholder="请输入波动分数"></el-input>
                </el-form-item>
              </el-form>
            </div>
            <div class="btnBox" :class="{ autoScoreBtnBox: courseData.notMarkTaskCount > 0 }">
              <div style="width: 32px" />
              <button class="endClasBtn" @click="handleEndCourse" v-if="                
                  currItem.state !== '已结课不可选'
                ">
                强制结课
              </button>
              <button v-if="courseData.notPassStuCount > 0" class="autoScore" @click="validator">
                自动评分
              </button>
              <span class="back" @click="back">返回</span>
            </div>
          </div>
        </el-dialog>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// (isAutoScore || courseData.notMarkTaskCount === 0) &&
import { getqueryreport, endCurrCourse, autoScore } from "@/request/teacher";
import { mapState } from "vuex";
import { parse } from "qs";
export default {
  data() {
    var checkDScore = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("默认分数不能为空"));
      }
      if (isNaN(Number(value))) {
        return callback(new Error("请输入数字值"));
      } else {
        if (Number(value) > 100) {
          return callback(new Error("数值不能大于100"));
        } else {
          callback();
        }
      }
    };
    var checkVMark = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("波动分数不能为空"));
      }
      if (isNaN(Number(value))) {
        return callback(new Error("请输入数字值"));
      } else {
        if (Number(value) > 100) {
          return callback(new Error("数值不能大于100"));
        } else if (Number(value) > Number(this.form.defaultTaskScore)) {
          return callback(new Error("波动分数不能大于默认分数"));
        } else {
          callback();
        }
      }
    };
    return {
      dialogVisible: false,
      courseData: {
        finishStuCount: 0,
        hasMarkTaskCount: 0,
        notFinishStuCount: 0,
        notMarkTaskCount: 0,
        notPassStuCount: 0,
        passStuCount: 0,
        totalStuCount: 0,
        totalTaskCount: 0,
      },
      beforeEndDialog: false,
      getReportLoading: false, // 正在加载结课报告
      showState: "",
      form: {
        defaultTaskScore: 80,
        varmark: 15,
      },
      rules: {
        defaultTaskScore: [{ validator: checkDScore, trigger: "blur" }],
        varmark: [{ validator: checkVMark, trigger: "blur" }],
      },
      isAutoScore: false,
      autoScoring: false, // 正在自动评分
    };
  },
  props: {
    showDialog: Boolean,
    currItem: Object,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  watch: {
    showDialog(n) {
      this.dialogVisible = n;
    },
    dialogVisible(n, o) {
      if (!n) {
        this.$parent.showDialog = false;
      }
    },
    currItem() {
      this.getReportLoading = true;
      this.fetchCourseData();
    },
  },
  filters: {
    rounding(val) {
      return !isNaN(val) ? Math.round(val * 100) : 0;
    },
  },
  created() {},
  methods: {
    handleClose() {
      this.$emit("handleClose");
    },
    handleToCourseStatistics() {
      this.$router.push({
        name: "courseStatistics",
        query: {
          currNo: this.currItem.currNo,
          courseID: this.currItem.courseID,
        },
        params: {
          id: this.currItem.currNo,
        },
      });
    },
    handleEnd() {
      if (this.courseData.notMarkTaskCount > 0) {
        this.showState = "noMarkTask";
        this.beforeEndDialog = true;
      } else if (this.courseData.notFinishStuCount > 0) {
        this.showState = "notFinishStu";
        this.beforeEndDialog = true;
      } else {
        this.endCourse(false);
        // this.showState = "";
        // this.beforeEndDialog = true;
      }
    },
    async endCourse(isCancel) {
      let params = {
        userID: this.userInfo.userID,
        currNo: this.currItem.currNo,
        isCancel: isCancel ? true : undefined,
      };
      const result = await this.$store.dispatch("courses/endCourse", {params: params, isCancel: isCancel})
      if (result == "catch") {
        this.beforeEndDialog = false;
      } else if (result) {
        this.showState = "";
        this.beforeEndDialog = false;
        this.$emit("handleEndCourse", !isCancel);
      } else {
        this.showState = "";
        this.beforeEndDialog = false;
      }
      // endCurrCourse(params)
      //   .then((res) => {
      //     if (res.errno === 0) {
      //       this.$antdMessage.success({
      //         content: isCancel ? "取消结课" : "结课成功!",
      //       });
      //       this.showState = "";
      //       this.beforeEndDialog = false;
      //       this.$emit("handleEndCourse", !isCancel);
      //     } else {
      //       this.$antdMessage.error({
      //         content: res.message || "结课失败!",
      //       });
      //       this.showState = "";
      //       this.beforeEndDialog = false;
      //     }
      //   })
      //   .catch((err) => {
      //     this.beforeEndDialog = false;
      //   });
    },
    handleEndCourse() {
      this.endCourse(false);
    },
    cancelEndClass() {
      this.endCourse(true);
    },
    fetchCourseData() {
      getqueryreport({
        currNo: Number(this.currItem.currNo),
      })
        .then((data) => {
          if (data) {
            this.courseData = data;
          } else {
            this.$antdMessage.error({
              content: "获取课程信息失败！",
            });
            this.$emit("handleClose");
          }
          this.getReportLoading = false;
        })
        .catch((err) => {
          this.getReportLoading = false;
        });
    },
    back() {
      this.showState = "";
      this.beforeEndDialog = false;
    },
    validator() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.confirmAutoScore();
        } else {
          return false;
        }
      });
    },
    confirmAutoScore() {
      const params = {
        currNo: Number(this.currItem.currNo),
        userID: this.userInfo.userID,
        defaultTaskScore: Number(this.form.defaultTaskScore),
        varmark: Number(this.form.varmark),
      };
      this.autoScoring = true;
      autoScore(params)
        .then((res) => {
          if (res.errno === 0) {
            this.$antdMessage.success({
              content: res.message || "评分成功",
            });
            this.isAutoScore = true;
          } else {
            this.$antdMessage.error({
              content: res.message,
            });
          }
          this.autoScoring = false;
        })
        .catch((err) => {
          this.$antdMessage.error({
            content: err,
          });
          this.autoScoring = false;
        });
    },
  },
};
</script>

<style lang="stylus">
.endClassDialog {
  margin-top: 10vh !important;
  margin-bottom: 0 !important;
  width: 592px !important;
  min-height: 808px !important;
  background-color: #ffffff !important;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.16) !important;
  border-radius: 10px !important;
  background-image: url('~@/assets/images/endClassbg.png') !important;

  .el-dialog__header {
    display: none;
  }

  .el-dialog__body {
    padding: 0;

    .endClassDialog_content {
      min-height: 808px;
      padding-top: 25px;

      .title {
        font-family: Microsoft YaHei;
        font-size: 3rem;
        color: #025183;
        font-weight: bold;
        text-align: center;
        // line-height: 1;
      }

      .courseName {
        margin-top: 10px;
        font-family: Microsoft YaHei;
        font-size: 3rem;
        color: #000000;
        font-weight: bold;
        text-align: center;
        // line-height: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .endClassDialogInfo {
        margin: 10px auto 0;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        width: 350px;
        height: 420px;

        .endClassDialogInfo_left {
          .taskStus {
            margin-top: 20px;

            .finishTaskCount {
              font-family: Microsoft YaHei;
              font-size: 1rem;
              color: #707070;
              font-weight: bold;
            }

            .uFinishTaskCount {
              font-family: Microsoft YaHei;
              font-size: 1rem;
              color: #000000;
              font-weight: bold;
            }
          }

          .reviewTask {
            margin-top: 25px;

            .FinishreviewTask {
              font-family: Microsoft YaHei;
              font-size: 1rem;
              color: #707070;
              font-weight: bold;
            }

            .uFinishreviewTask {
              font-family: Microsoft YaHei;
              font-size: 1rem;
              color: #000000;
              font-weight: bold;
            }
          }

          .scoreCount {
            margin-top: 25px;

            .cBlack {
              font-family: Microsoft YaHei;
              font-size: 1rem;
              color: #000000;
              font-weight: bold;
            }

            .score {
              font-family: Microsoft YaHei;
              font-size: 1rem;
              color: #707070;
            }
          }

          .chooseCourseCount {
            font-family: Microsoft YaHei;
            font-size: 1rem;
            color: #000000;
            font-weight: bold;
          }

          .courseInfo {
            margin-top: 15px;

            .teacher {
              font-family: Microsoft YaHei;
              font-size: 1rem;
              color: #000000;
              font-weight: bold;
            }

            .taskCoutn, .courseTime, .courseCredit {
              font-family: Microsoft YaHei;
              font-size: 1rem;
              color: #707070;
            }
          }
        }

        .endClassDialogInfo_right {
          margin-top: 40px;

          .title {
            font-family: Microsoft YaHei;
            font-size: 1rem;
            color: #000000;
            font-weight: bold;
          }

          .percentage {
            font-family: Microsoft YaHei;
            font-size: 2rem;
            color: #000000;
            font-weight: bold;
          }
        }
      }

      button {
        cursor: pointer;
      }

      .checkInfoBtn {
        margin-top: 45px;
        text-align: center;
        line-height: 1;

        button {
          width: 386px;
          height: 50px;
          background-color: #4c19a7;
          border-radius: 25px;
          border: none;
          font-family: Microsoft YaHei;
          font-size: 1rem;
          color: #ffffff;
          font-weight: bold;
        }
      }

      .endClassBtn-cancel {
        width: 386px;
        margin: 25px auto 0;
        display: flex;
        justify-content: space-between;
        text-align: center;

        .endClassBtn, .cancelEndClassBtn {
          width: 252px;
          height: 50px;
          background-color: #f6ad35;
          border-radius: 24px;
          font-family: Microsoft YaHei;
          font-size: 20px;
          color: #ffffff;
          border: none;
          font-weight: bold;
        }

        .cancelEndClassBtn {
          background-color: #ff4d4d;
        }

        .cancel {
          margin-right: 18px;
          width: 50px;
          height: 50px;
          border: solid 1px #000000;
          font-family: Microsoft YaHei;
          font-size: 16px;
          color: #000000;
          background: transparent;
          border-radius: 50%;
        }
      }
    }
  }
}

.checkBeforeEndState {
  margin-top: 30vh !important;
  padding-bottom: 20px;
  width: 426px !important;
  min-height: 270px;
  border-radius: 10px !important;

  .el-form {
    margin-top: 10px;

    .el-form-item__label {
      width: 100px !important;
    }

    .el-input {
      width: auto;
    }
  }

  .el-dialog__header {
    display: none;
  }

  .el-dialog__body {
    padding-top: 100px;
    padding-bottom: 0;
  }

  .tips {
    text-align: center;
    font-family: Microsoft YaHei;
    font-size: 20px;
    font-weight: bold;
    color: #0c0000;
  }

  .btnBox {
    margin: 0 auto;
    width: 300px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 80px;

    .endClasBtn, .autoScore {
      cursor: pointer;
      width: 132px;
      height: 39px;
      background-color: #ff4d4d;
      border-radius: 30px;
      border: none;
      font-family: Microsoft YaHei;
      font-size: 16px;
      color: #ffffff;
      font-weight: bold;
    }

    .autoScore {
      margin: 0 10px;
      background-color: #2586fe;
    }

    .back {
      cursor: pointer;
      font-family: Microsoft YaHei;
      font-size: 16px;
      color: rgba(0, 0, 0, 0.5);
      font-weight: bold;
    }
  }

  .autoScoreBtnBox {
    margin-top: 30px;
  }
}
</style>